<?php
    // 这是个添加文章接口
    include_once '../../fn.php';

    // echo '<pre>';
    // print_r($_POST);
    // echo '</pre>';

    // echo '<pre>';
    // print_r($_FILES);
    // echo '</pre>';

    // 保存普通表单数据
    $title = $_POST['title'];
    $content = $_POST['content'];
    $slug = $_POST['slug'];
    $category = $_POST['category'];
    $created = $_POST['created'];
    $status = $_POST['status'];

    // 保存文件数据
    if ($_FILES['feature']['error']===0) {
        // 错误码为0即正确上传才处理

        // 重铸文件名
        $firstName = explode('.',$_FILES['feature']['name'])[0];
        $lastName = explode('.',$_FILES['feature']['name'])[1];

        $newName = date('YmdHis',time()) . '-' . $firstName . '.' . $lastName;

        // echo $newName;
        // 图片是多个页面共享的,尽量存储相对路径,我们确定图片一定放在uploads,目录层级不能确定
        $path = 'uploads/' . $newName;
        // 移动文件
        move_uploaded_file($_FILES['feature']['tmp_name'],'../../' . $path);

        $feature = $path;
    }

    // 开启session 根据浏览器cookie里存的sessionid去服务器找同名文件里存的用户id
    session_start();
    $userId = $_SESSION['user_id'];

    // 构建sql插入串
    $sql = "insert into posts (slug, title, feature, created, content, views, likes, status, user_id, category_id) 
            values ('$slug', '$title', '$feature ', '$created', '$content', 0, 0, '$status', '$userId', '$category');";

    // echo $sql;

    $result = my_exec($sql);

    echo json_encode($result);

    header('location: ../posts.php');

?>